import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Layout, SearchBox, DatePicker, Button, Table, Pagination, Bubble } from 'tea-component';
import * as actionTypes from '@src/model/actionType';
import { timeFormatYMDHms, getQueryVariable, abbreviation } from '@src/utils/index';
import moment from 'moment';
import { Link } from 'react-router-dom';
import { Bread } from '@src/components/common-compinents';

const bread = Bread;
const { Content } = Layout;
const { autotip, scrollable } = Table.addons;

const DEFAULT_PAGE_INDEX = 1;
const DEFAULT_PAGE_SIZE = 10;

export function TransactionList(props) {
  const chainId = decodeURIComponent(getQueryVariable('chainid') || '');
  const { history } = props;
  const dispatch = useDispatch();
  const fetchTxList = ({
    searchInput = '',
    startTime = 0,
    endTime = 0,
    pageIndex = DEFAULT_PAGE_INDEX,
    pageSize = DEFAULT_PAGE_SIZE,
  }) => {
    dispatch({
      type: actionTypes.fetchTxList,
      params: {
        ChainId: chainId,
        TxId: searchInput,
        BlockHash: '',
        StartTime: startTime,
        EndTime: endTime,
        Offset: pageIndex - 1,
        Limit: pageSize,
      },
    });
  };

  // @ts-ignore
  const txListStore = useSelector((state) => state.txListReducer);

  useEffect(() => {
    fetchTxList({ searchInput: searchInput });
  }, [dispatch]);

  const [searchInput, setSearchInput] = useState('');
  const searchInputHandle = (val) => {
    setSearchInput(val);
  };
  const [startTime, setStartTime] = useState(0);
  const startTimeHandle = (value) => {
    setStartTime(moment(value).unix());
  };
  const [endTime, setEndTime] = useState(0);
  const endTimeHandle = (value) => {
    setEndTime(moment(value).unix());
  };

  const [pageIndex, setPageIndex] = useState(DEFAULT_PAGE_INDEX);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  const searchHandle = () => {
    setPageIndex(DEFAULT_PAGE_INDEX);
    fetchTxList({ searchInput, startTime, endTime, pageIndex: DEFAULT_PAGE_INDEX, pageSize });
  };

  const onPagingChange = ({ pageIndex, pageSize }) => {
    setPageIndex(pageIndex);
    setPageSize(pageSize);
    fetchTxList({ searchInput, startTime, endTime, pageIndex, pageSize });
  };
  return (
    <Content>
      <Content.Header
        showBackButton
        onBackButtonClick={() => {
          history.goBack();
        }}
        title={bread('区块链浏览器/交易列表')}
      />
      <Content.Body>
        <div
          style={{
            width: '1000px',
            boxSizing: 'border-box',
            margin: '0px auto',
            display: 'flex',
            marginBottom: '10px',
          }}
        >
          <SearchBox
            style={{ width: '230px', marginRight: '12px' }}
            placeholder="输入交易ID"
            value={searchInput}
            onChange={searchInputHandle}
          />
          <DatePicker
            showTime
            clearable
            onChange={startTimeHandle}
            style={{ marginRight: '12px' }}
            placeholder="开始时间"
            value={startTime ? moment.unix(startTime) : null}
          />
          <DatePicker
            showTime
            clearable
            onChange={endTimeHandle}
            style={{ marginRight: '12px' }}
            placeholder="结束时间"
            value={endTime ? moment.unix(endTime) : null}
          />
          <Button type="primary" onClick={searchHandle}>
            筛 选
          </Button>
        </div>
        <Table
          style={{ width: '1000px', margin: '0px auto' }}
          verticalTop
          records={txListStore.transactionList.GroupList}
          recordKey="Id"
          bordered={true}
          columns={[
            {
              key: 'TxId',
              header: '交易ID',
              // @ts-ignore
              render: (row) => {
                return (
                  <Bubble
                    arrowPointAtCenter
                    placement="top"
                    content={
                      // @ts-ignore
                      row.TxId
                    }
                  >
                    <Link
                      style={{ color: 'rgba(0, 0, 0, 0.9)', textDecoration: 'none' }}
                      // @ts-ignore
                      to={`/tsdetail?id=${encodeURIComponent(row.Id)}&tp=ts&chainid=${encodeURIComponent(chainId)}`}
                    >
                      {abbreviation(
                        // @ts-ignore
                        row.TxId,
                      )}
                    </Link>
                  </Bubble>
                );
              },
            },
            {
              key: 'Sender',
              header: '交易发送者',
              width: 150,
            },
            {
              key: 'BlockHash',
              header: '所属区块哈希',
              // @ts-ignore
              render: (row) => {
                return (
                  <Bubble
                    arrowPointAtCenter
                    placement="top"
                    content={
                      // @ts-ignore
                      row.BlockHash
                    }
                  >
                    {abbreviation(
                      // @ts-ignore
                      row.BlockHash,
                    )}
                  </Bubble>
                );
              },
            },
            {
              key: 'Timestamp',
              header: '创建时间',
              width: 200,
              // @ts-ignore
              render: (row) => <span>{timeFormatYMDHms(row.Timestamp)}</span>,
            },
            {
              key: 'settings',
              header: '操作',
              width: 100,
              render: (row) => (
                <Button
                  type="link"
                  onClick={() => {
                    // @ts-ignore
                    history.push(
                      `/tsdetail?id=${encodeURIComponent(row.Id)}&tp=ts&chainid=${encodeURIComponent(chainId)}`,
                    );
                  }}
                >
                  查看
                </Button>
              ),
            },
          ]}
          addons={[
            scrollable({
              maxHeight: 480,
            }),
            autotip({}),
          ]}
        />
        <Pagination
          recordCount={txListStore.transactionList.TotalCount}
          pageIndex={pageIndex}
          pageSize={pageSize}
          style={{ backgroundColor: '#fff', width: '1000px', padding: '14px 20px' }}
          onPagingChange={onPagingChange}
        />
      </Content.Body>
    </Content>
  );
}
